package cn.yshujia.ex;

import cn.yshujia.domain.vo.ApiVO;
import cn.yshujia.enums.Info;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author YShuJia
 * @description 全局异常处理类
 * @create 2024/4/23
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
	
	@ExceptionHandler (DefineExceptionHandler.class)
	public ApiVO<Boolean> resultException(DefineExceptionHandler e) {
		log.error("自定义异常：{}", e.getLocalizedMessage());
		return ApiVO.error(e.getCode(), e.getMessage());
	}
	
	@ExceptionHandler (value = IllegalArgumentException.class)
	public ApiVO<Boolean> handler(IllegalArgumentException e) {
		log.error("参数异常：{}", e.getLocalizedMessage());
		if (null != e.getCause() && e.getCause() instanceof DefineExceptionHandler) {
			return ApiVO.error(((DefineExceptionHandler) e.getCause()).getCode(), e.getCause().getMessage());
		}
		return ApiVO.error(Info.SERVER_ERROR.getCode(), Info.SERVER_ERROR.getMessage());
	}
	
	@ExceptionHandler (value = AccessDeniedException.class)
	public ApiVO<Boolean> handler(AccessDeniedException e) {
		log.error("访问被拒绝异常：{}", e.getLocalizedMessage());
		return ApiVO.error(Info.UNAUTHORIZED.getCode(), Info.UNAUTHORIZED.getMessage());
	}
	
	@ExceptionHandler (value = NullPointerException.class)
	public ApiVO<Boolean> handler(NullPointerException e) {
		log.error("空指针异常：{}", e.getLocalizedMessage());
		return result(e);
	}
	
	@ExceptionHandler (value = NumberFormatException.class)
	public ApiVO<Boolean> handler(NumberFormatException e) {
		log.error("数字格式化异常：{}", e.getLocalizedMessage());
		return result(e);
	}
	
	@ExceptionHandler (value = RuntimeException.class)
	public ApiVO<Boolean> handler(RuntimeException e) {
		log.error("运行时异常：{}", e.getLocalizedMessage());
		return result(e);
	}
	
	@ExceptionHandler (value = Exception.class)
	public ApiVO<Boolean> handler(Exception e) {
		log.error("异常：{}", e.getLocalizedMessage());
		return result(e);
	}
	
	private ApiVO<Boolean> result(Exception e) {
		if (null != e.getCause() && e.getCause() instanceof DefineExceptionHandler) {
			return ApiVO.error(((DefineExceptionHandler) e.getCause()).getCode(), e.getCause().getMessage());
		}
		return ApiVO.error(Info.SERVER_ERROR.getCode(), Info.SERVER_ERROR.getMessage());
	}
}
